package com.dge.common.utils

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.dge.common.common.AppConfig
import com.dge.common.manager.ActivityStackManager
import com.dge.common.other.IOSStyleDialogAnimator
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import timber.log.Timber

/**
 * @time 2022/7/26 11:06
 * @des 全局的loading dialog，防止dialog重复显示
 */
object LoadingDialogUtils {
    private const val WHAT_SHOW_LOADING = 0x01
    private const val WHAT_HIDE_LOADING = 0x02
    private val handler = LoadingHandler()
    val dialogMap: HashMap<String, LoadingPopupView> = HashMap()

    fun onActivityFinishing(activity: Activity) {
        val localClassName = activity.localClassName
        val dialog = dialogMap.remove(localClassName)
        if (AppConfig.isDebug()) {
            Timber.d("onActivityFinishing ${getTag(localClassName)} hideLoading dialog != null is ${dialog != null}")
        }
        if (dialog != null) {
            try {
                handler.removeMessages(WHAT_SHOW_LOADING, localClassName)
                handler.removeMessages(WHAT_HIDE_LOADING, localClassName)
                dialog.dismiss()
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                dialog.destroy()
            }
        }
        if (localClassName == "ui.home.ui.MainActivity") { //最底层的activity销毁了，需要移除所有dialog
            handler.removeMessages(WHAT_SHOW_LOADING)
            handler.removeMessages(WHAT_HIDE_LOADING)
            dialogMap.values.forEach {
                it.destroy()
            }
            dialogMap.clear()
        }
    }

    fun onActivityStop(activity: Activity) {
        val localClassName = activity.localClassName
        val dialog = dialogMap[localClassName]
        if (AppConfig.isDebug()) {
            Timber.d("onActivityStop ${getTag(localClassName)} hideLoading dialog != null is ${dialog != null}")
        }
        if (dialog != null) {
            try {
                handler.removeMessages(WHAT_SHOW_LOADING, localClassName)
                handler.removeMessages(WHAT_HIDE_LOADING, localClassName)
                dialog.dismiss()
            } catch (e: Exception) {
            }
        }
    }

    private fun initLoadingView(activity: Activity? = null, msg: String? = null): LoadingPopupView? {
        val context = activity ?: getContext() ?: return null
        return XPopup.Builder(context)
            .hasShadowBg(true)
            .isDarkTheme(AppConfig.isDarkTheme())
            .customAnimator(IOSStyleDialogAnimator())
            .isLightStatusBar(true)
            .isRequestFocus(false) //不请求焦点，防止statusbar闪烁
            .asLoading(msg ?: "请稍候")
    }

    fun showLoading(
        activity: Activity? = null,
        msg: String? = null,
        dismissOnBackPressed: Boolean = true,
        dismissOnTouchOutside: Boolean = true,
        isLightStatusBar: Boolean = true
    ) {
        val ac = activity ?: ActivityStackManager.getInstance().getTopActivity()
        if (isFinished(ac)) return
        val localClassName = ac?.localClassName
        val loadingDialog = if (localClassName != null) {
            val dialog = dialogMap[localClassName]
            if (dialog?.popupInfo != null) {
                dialog.setTitle(msg ?: "请稍候")
                dialog
            } else {
                dialogMap.remove(localClassName)
                initLoadingView(ac, msg ?: "请稍候")
            }
        } else {
            return
        }
        if (loadingDialog != null) {
            dialogMap[localClassName] = loadingDialog
        }
        handler.removeMessages(WHAT_SHOW_LOADING, localClassName)
        loadingDialog?.popupInfo?.isDismissOnBackPressed = dismissOnBackPressed
        loadingDialog?.popupInfo?.isDismissOnTouchOutside = dismissOnTouchOutside
        loadingDialog?.popupInfo?.isLightStatusBar = if (isLightStatusBar) 1 else -1
        // synchronized(LoadingDialogUtils.javaClass) {
        //     LoadingDialogUtils.loadingDialog = loadingDialog
        // }
        val message = handler.obtainMessage(WHAT_SHOW_LOADING, localClassName)
        handler.removeMessages(WHAT_HIDE_LOADING, localClassName)
        message.sendToTarget()
    }

    fun showLoading() {
        showLoading(null, null, dismissOnBackPressed = true, dismissOnTouchOutside = true, isLightStatusBar = true)
    }

    fun showLoading(msg: String) {
        showLoading(null, msg, dismissOnBackPressed = true, dismissOnTouchOutside = true, isLightStatusBar = true)
    }

    fun showLoading(activity: Activity) {
        showLoading(activity, null, dismissOnBackPressed = true, dismissOnTouchOutside = true, isLightStatusBar = true)
    }

    fun showLoading(activity: Activity, msg: String) {
        showLoading(activity, msg, dismissOnBackPressed = true, dismissOnTouchOutside = true, isLightStatusBar = true)
    }

    fun hideLoading() {
        val activity = ActivityStackManager.getInstance().getTopActivity()
        if (isFinished(activity)) return
        hideLoading(activity!!, false)
    }

    fun hideLoading(activity: Activity, isHideDelay: Boolean = false) {
        if (isFinished(activity)) return
        val localClassName = activity.localClassName
        val dialog = dialogMap[localClassName]
        if (dialog?.isShow == true || isHideDelay) {
            val message = handler.obtainMessage(WHAT_HIDE_LOADING, localClassName)
            handler.sendMessageDelayed(message, 300)
        } else {
            handler.removeMessages(WHAT_HIDE_LOADING, localClassName)
            dialog?.apply {
                if (AppConfig.isDebug()) {
                    Timber.d("${getTag(localClassName)} hideLoading")
                }
                dismiss()
            }
        }
    }

    private fun isFinished(activity: Activity? = null): Boolean {
        val ac = activity ?: ActivityStackManager.getInstance().getTopActivity()
        return ac?.isFinishing ?: true
    }

    private fun getContext(): Context? {
        return ActivityStackManager.getInstance().getTopActivity()
    }

    class LoadingHandler : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                WHAT_SHOW_LOADING -> {
                    val name = msg.obj as String
                    val dialog = dialogMap[name]
                    if (dialog != null) {
                        if (dialog.popupInfo == null) {
                            return
                        }
                        if (AppConfig.isDebug()) {
                            Timber.d("${getTag(name)} showLoading")
                        }
                        dialog.show()
                    }
                    // else {
                    //     if (loadingDialog == null || loadingDialog!!.context !is Activity || (loadingDialog!!.context as Activity).localClassName != name) return
                    //     if ((loadingDialog!!.context as Activity).isFinishing || loadingDialog?.popupInfo == null) {
                    //         return
                    //     }
                    //     loadingDialog?.show()
                    // }
                }

                WHAT_HIDE_LOADING -> {
                    val name = msg.obj as String
                    val dialog = dialogMap[name]
                    if (dialog != null) {
                        if (dialog.popupInfo == null) {
                            dialogMap.remove(name)?.destroy()
                            return
                        }
                        if (AppConfig.isDebug()) {
                            Timber.d("${getTag(name)} hideLoading")
                        }
                        dialog.dismiss()
                    }
                    // else {
                    //     if (loadingDialog == null || loadingDialog!!.context !is Activity || (loadingDialog!!.context as Activity).localClassName != name) return
                    //     if ((loadingDialog!!.context as Activity).isFinishing || loadingDialog?.popupInfo == null) {
                    //         return
                    //     }
                    //     loadingDialog?.dismiss()
                    // }
                }
            }
        }
    }

    private fun getTag(name: String): String {
        val index = name.lastIndexOf(".")
        return if (index > 0 && index + 1 < name.length) {
            name.substring(index + 1)
        } else {
            name
        }
    }
}